using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

using Wicresoft.Messages.BusinessLogic;
using Wicresoft.Messages.Entity;
using Wicresoft.Messages.Implementation;
using Wicresoft.Messages.Interface;

namespace Wicresoft.Messages.Interface
{
    class OutgoingProcessorFactory
    {
        public static IOutgoingProcessor CreateOutgoingProcessor(int outgoingProcessorType)
        {
            if (_outgoingProcessFactory.ProcessorCache[outgoingProcessorType] == null)
            {
                System.Diagnostics.Debug.WriteLine("if (_outgoingProcessFactory.ProcessorCache[outgoingProcessorType] == null)");
                Device device = BLMessage.GetSingleDevice(outgoingProcessorType);
                try
                {
                    string assemblyFilename = device.AssemblyName;
                    string className = device.OutgoingClassName;
                    Assembly currentAssembly = Assembly.GetAssembly(typeof(OutgoingProcessorFactory));
                    string assemblyFullname = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), assemblyFilename);
                    Assembly assembly = Assembly.LoadFile(assemblyFullname);
                    Type type = assembly.GetType(className);
                    IOutgoingProcessor processor = Activator.CreateInstance(type) as IOutgoingProcessor;
                    _outgoingProcessFactory.ProcessorCache[outgoingProcessorType] = processor;
                    System.Diagnostics.Debug.WriteLine("_outgoingProcessFactory.ProcessorCache[outgoingProcessorType] = processor;");
                }
                catch(Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                    try
                    {
                        _outgoingProcessFactory.ProcessorCache[outgoingProcessorType] = Activator.CreateInstance(typeof(WebOutgoingProcessor)) as IOutgoingProcessor;

                    }
                    catch (Exception exx)
                    {
                        System.Diagnostics.Debug.WriteLine(exx.Message);
                        System.Diagnostics.Debug.WriteLine(exx.StackTrace);
                    }
                }
            }
            return _outgoingProcessFactory.ProcessorCache[outgoingProcessorType] as IOutgoingProcessor;
        }

        private static OutgoingProcessorFactory _outgoingProcessFactory = new OutgoingProcessorFactory();
        private Hashtable ProcessorCache = new Hashtable();
    }
}
